import json
from tkinter import INSERT
import pymysql


conn = pymysql.connect(user='root',passwd='lzf990507',db='alumni_book_db',autocommit=True)

cursor = conn.cursor()


def load_data():
    with open("./china.json") as f:
        return f.read()


def gen_city_set(raw_data):
    load_json = json.loads(raw_data)
    city_set = load_json["features"]
    for city in city_set:
        raw_str = (city["properties"]["name"])

        if len(raw_str)!=0:
            yield raw_str

def insert_to_db(id,name):
    try:
        sql = "INSERT INTO t_province (`name`) VALUES('%s')" % (name)
        print(sql)
        cursor.execute(sql)
    except Exception as e:
        conn.rollback()
        print(e)


def main():
    raw_data = load_data()
    city_set = gen_city_set(raw_data)
    for idx,city in enumerate(city_set):
        insert_to_db(idx,city)

if __name__ == '__main__':
    main()
    